// 获取window的引用:
const $window = $(window);
// 获取包含data-src属性的img，并以jQuery对象存入数组:
// const lazyImgs = $('img[data-src]');

//获取屏幕像素密度
const ratio = window.devicePixelRatio;
var lazyImgs = [];

function loadImg(option) {
    const img = new Image();
    img.src = option.src;
    img.onload = () => {
        option.onload && option.onload();
    };
    img.onerror = () => {
        option.onerror && option.onerror();
    };
}

function setImgUrl(elment) {
    const oldSrc = elment.attr("src");
    // 设置src属性:
    const imgSrc = elment.attr("data-src");
    //裁剪方法
    const cropType = elment.attr("data-crop-type");

    //裁剪高度
    const cropHeight = elment.attr("data-crop-height");

    //裁剪宽带
    const cropWidth = elment.attr("data-crop-width");

    //如果有src属性加载src
    if (imgSrc) {
        const splitStr = imgSrc.indexOf("?") === -1 ? "?" : "&";
        const fileExtension = imgSrc.substring(imgSrc.lastIndexOf(".") + 1);

        //默认宽度裁剪
        const width = cropWidth || elment.innerWidth();
        let src = width ? `${imgSrc}${splitStr}x-oss-process=image/resize,m_lfit,w_${Math.floor(width * (ratio > 1 ? ratio : 1.5))}` : imgSrc;

        //高度裁剪
        if (cropType === "height") {
            const height = cropHeight || elment.height();
            src = height ? `${imgSrc}${splitStr}x-oss-process=image/resize,m_lfit,h_${Math.floor(height * (ratio > 1 ? ratio : 1.5))}` : imgSrc;
        }

        //如果图片等于 webp 、svg 、icon、ico 不裁剪
        if (fileExtension === "webp" || fileExtension === "svg" || fileExtension === "icon" || fileExtension === "ico") {
            src = imgSrc;
        }

        if (elment.attr("data-aspect-ratio")) {
            return false;
        }
        loadImg({
            src: src,
            onload: function () {
                elment.attr("src", src);
                moi.onEvent("lazyImg", imgSrc);
            },
            onerror: function () {
                elment.attr("src", oldSrc);
            }
        });
        elment[0].removeAttribute("data-src");
    } else {
        elment[0].removeAttribute("data-src");
    }
}

//加载图片
function lazyImageShow() {
    // 获取页面滚动的高度:
    const wtop = $window.scrollTop();
    // 判断是否还有未加载的img:
    if (lazyImgs.length > 0) {
        // 获取可视区域高度:
        const wheight = $window.height();
        const delIndexs = [];
        for (let i = 0; i < lazyImgs.length; i++) {
            const $i = lazyImgs[i];
            // 判断是否在可视范围内:
            //  && elment.is(":visible")
            if ($i.offset().top - wtop - 100 < wheight && elment.is(":visible")) {
                delIndexs.push(i);
                setImgUrl($i);
            }
        }

        for (let i = delIndexs.length - 1; i >= 0; i--) {
            lazyImgs.splice(delIndexs[i], 1);
        }
    }
}

const imgObserver = IntersectionObserver
    ? new IntersectionObserver(
          function (entrys) {
              for (const entry of entrys) {
                  if (entry.intersectionRatio > 0) {
                      const element = $(entry.target);
                      setImgUrl(element);
                  }
              }
          },
          { rootMargin: "0px 0px 100px 0px", threshold: [0.01] }
      )
    : "";

// 定义事件函数:
const onScroll = function () {
    if (!IntersectionObserver) {
        lazyImageShow();
    }
};

// 绑定事件:
$window.scroll(onScroll);

//懒加载
window.lazyImageShow = lazyImageShow;

window.addLazyImages = function (nodes) {
    nodes.each(function () {
        if (IntersectionObserver) {
            imgObserver.observe(this);
        } else {
            lazyImgs.push($(this));
        }
    });
    onScroll();
};
